<template>
  <div>
<!--    <el-form :model="searchForm" size="small" :inline="true" ref="searchForm">
      <el-form-item prop="roleName">
        <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable style="width: 240px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getRoleList($event)">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="reset($event)">重置</el-button>
      </el-form-item>
    </el-form>-->

    <div>
      <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable style="width: 240px" size="small"/>
      <el-button type="primary" icon="el-icon-search" size="mini" @click="btnGet($event)" style="margin-left: 10px">搜索</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="reset($event)">重置</el-button>
    </div>

    <el-row :gutter="10" class="mb8" style="margin-top: 20px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="dialogVisible = true">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popconfirm title="确定删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" slot="reference">删除</el-button>
        </el-popconfirm>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini">导出</el-button>
      </el-col>
    </el-row>

    <el-table :data="tableData" tooltip-effect="dark" @selection-change="handleSelectionChange" style="padding-top: 15px" ref="multipleTable">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色编号" prop="id" width="120" />
      <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="权限字符" prop="code" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.statu"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" align="center" prop="remark" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="text" @click="permHandle(scope.row.id)">分配权限</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id)">修改</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.id)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>


    <!--新增对话框-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="600px"
        :before-close="handleClose">

      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-editForm">

        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="唯一编码" prop="code" label-width="100px">
          <el-input v-model="editForm.code" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('editForm')">立即创建</el-button>
          <el-button @click="resetForm('editForm')">重置</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>

    <el-dialog
        title="分配权限"
        :visible.sync="permDialogVisible"
        width="600px">

      <el-form :model="permForm">

        <el-tree
            :data="permTreeData"
            show-checkbox
            ref="permTree"
            :default-expand-all=true
            node-key="id"
            :check-strictly=true
            :props="defaultProps">
        </el-tree>

      </el-form>

      <span slot="footer" class="dialog-footer">
			    <el-button @click="permDialogVisible = false">取 消</el-button>
			    <el-button type="primary" @click="submitPermFormHandle('permForm')">确 定</el-button>
			</span>

    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Role",
  data() {
    return {
      searchForm: {},

      total: 0,
      size: 10,
      current: 1,
      single: true,
      multiple: true,
      dialogVisible: false,
      editForm: {

      },
      statusForm:{

      },

      tableData: [],

      editFormRules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入唯一编码', trigger: 'blur'}
        ],
        statu: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ]
      },

      multipleSelection: [],

      permDialogVisible: false,
      permForm: {},
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      permTreeData: []
    }
  },
  created() {
    this.getRoleList()

    this.request.get('/sys/menu/list').then(res => {
      this.permTreeData = res.data.data
    })

    var that = this;
    document.onkeydown = function(e) {
      var key = window.event.keyCode;
      if (key === 13 ) {
        if (that.name !== "" || that.description !== ""){
          that.getRoleList();
        }
      }
    }
  },
  methods: {
    /** 强制失去焦点  */
    focus(evt){
      const target = evt.target
      if (target.nodeName === 'SPAN') {
        target.parentNode.blur()
      }
      target.blur()
    },
    /** 重置按钮操作 */
    reset(evt) {
      this.searchForm.name = ''
      this.focus(evt)
      this.getRoleList()
    },
    btnGet(evt){
      this.focus(evt)
      this.getRoleList()
    },
    // 角色状态修改
    handleStatusChange(row) {
      this.statusForm.id = row.id
      this.statusForm.statu = row.statu
      this.request.post("/sys/role/changeStatus",this.statusForm).then(res => {
        if (res.data.code === '200'){
          this.$message.success("操作成功")
        }else {
          this.getRoleList()
          this.$message.error("操作失败")
        }
      })
    },
    handleSelectionChange(val) {
      console.log("勾选")
      console.log(val)
      this.multipleSelection = val;
      if (val.length > 0){
        this.multiple = false
      }
      if (val.length > 1){
        this.single = true
      }if (val.length === 0){
        this.multiple = true
        this.single = true
      }
      if (val.length === 1){
        this.single = false
      }
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val
      this.getRoleList()
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },

    getRoleList() {
      this.request.get("/sys/role/list", {
        params: {
          name: this.searchForm.name,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.request.post('/sys/role/' + (this.editForm.id?'update' : 'save'), this.editForm)
              .then(res => {

                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose:() => {
                    this.getRoleList()
                  }
                });

                this.dialogVisible = false
                this.resetForm(formName)
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id) {
      this.request.get('/sys/role/info/' + id).then(res => {
        this.editForm = res.data.data

        this.dialogVisible = true
      })
    },
    delHandle(id) {
      var ids = []
      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.id)
        })
      }
      console.log(ids)

      this.request.post("/sys/role/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose:() => {
            this.getRoleList()
          }
        });
      })
    },
    permHandle(id) {
      this.permDialogVisible = true

      this.request.get("/sys/role/info/" + id).then(res => {

        this.$refs.permTree.setCheckedKeys(res.data.data.menuIds)
        this.permForm = res.data.data
      })
    },

    submitPermFormHandle(formName) {
      var menuIds = this.$refs.permTree.getCheckedKeys()

      console.log(menuIds)

      this.request.post('/sys/role/perm/' + this.permForm.id, menuIds).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose:() => {
            this.getRoleList()
          }
        });
        this.permDialogVisible = false
        this.resetForm(formName)
      })
    }
  }
}
</script>

<style scoped>

</style>